<template>
	<view class="content">
		<view class="content_form">
			<uni-segmented-control :current="current" :values="subsectionList" :style-type="'button'"
				:active-color="'#2979ff'" @clickItem="sectionChange" />
			<uni-forms :model="formData" ref="form" :label-width="120" label-align="left" :rules="rules">
				<uni-forms-item label="收件人" prop="userRealName" required v-if="current == 0">
					<view style="width: 100%;margin-top: 10rpx;">
						<text style="color:#0960bd" @click="handleSelectUser(0)">选择</text>
						<text @click="handleCS" style="color:#0960bd;margin-left: 20rpx;">{{ iscs ? '删除抄送' : '添加抄送'
						}}</text>
						<view class="cus_tag" style="margin-top: 10rpx;">
							<view class="cus_tag_view" v-for="(item, index) in formData['hadUsers']" :key="item.key">{{
								item.title }}
								<uni-icons type="closeempty" @click="handleCloseTag(index, 0)"
									color='#2979ff'></uni-icons>
							</view>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="部门" prop="userRealName" required v-if="current == 1">
					<view style="width: 100%;margin-top: 10rpx;">
						<text style="color:#0960bd" @click="handleTkiTreeDepart()">选择</text>
						<text @click="handleCS" style="color:#0960bd;margin-left: 20rpx;">{{ iscs ? '删除抄送' : '添加抄送'
						}}</text>
						<view class="cus_tag" style="margin-top: 10rpx;">
							<view class="cus_tag_view" v-for="(item, index) in formData['hadDeptList']"
								:key="item.code">{{ item.name }}
								<uni-icons type="closeempty" @click="handleCloseTag(index, 3)"
									color='#2979ff'></uni-icons>
							</view>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="抄送" v-if="iscs">
					<view style="width: 100%;margin-top: 10rpx;">
						<text style="color:#0960bd" @click="handleSelectUser(1)">选择</text>
						<view class="cus_tag" style="margin-top: 10rpx;">
							<view class="cus_tag_view" v-for="(item, index) in formData['hadUsers1']" :key="item.key">{{
								item.title }}
								<uni-icons type="closeempty" @click="handleCloseTag(index, 1)"
									color='#2979ff'></uni-icons>
							</view>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="主题" prop="title" required>
					<uni-easyinput v-model="formData.title" placeholder="请填写主题"></uni-easyinput>
				</uni-forms-item>
				<LEditor v-model:value="formData.content" ref="lEditorRef" />
				<uni-forms-item label="附件">
					<FileUpload ref="fileUploadRef" :msgId="formData.id" />
				</uni-forms-item>
				<template v-if="ishj">
					<uni-forms-item label="发送时间" prop="send_now" required>
						<radio-group @change="handleChangeSendNow($event, 'send_now')">
							<view>
								<label>
									<radio color="#0097ff" :value="'yes'" :checked="formData.send_now === 'yes'" />立即发送
								</label>
							</view>
							<view style="margin-top: 10rpx;">
								<label style="display: flex;align-items: center;">
									<radio color="#0097ff" :value="'no'" :checked="formData.send_now === 'no'" /> 定时发送
									<view style="display: flex;gap:10rpx;align-items: center;margin-left: 10rpx;"
										@click="showTime = true">
										{{ formData.send_time }}
										<uni-icons type="down"></uni-icons>
									</view>
								</label>
							</view>
						</radio-group>
					</uni-forms-item>
					<uni-forms-item label="回执" prop="receipt_state" required>
						<radio-group @change="handleChangeSendNow($event, 'receipt_state')">
							<label v-for="(item, index) in receipt_stateList" :key="index" style="margin-right: 10rpx;">
								<radio color="#0097ff" :value="item.value" :checked="formData.receipt_state == item.value" />{{
									item.label
								}}
							</label>
						</radio-group>
					</uni-forms-item>
					<uni-forms-item label="等级" prop="msg_level" required>
						<radio-group @change="handleChangeSendNow($event, 'msg_level')">
							<label v-for="(item, index) in msg_levelList" :key="index" style="margin-right: 10rpx;">
								<radio color="#0097ff" :value="item.value" :checked="formData.msg_level == item.value" />{{ item.label
								}}
							</label>
						</radio-group>
					</uni-forms-item>
				</template>
			</uni-forms>
		</view>

		<view class="body_bottom">
			<template v-if="type == 'reply'">
				<view @click="handleSend('reply')">确定</view>
				<view @click="handleResetWrite()">重写</view>
			</template>
			<template v-else>
				<view @click="handleSend('send')">发送</view>
				<view @click="handleSend('draft')">保存草稿</view>
				<view @click="handleShowMore">高级功能</view>
			</template>
		</view>
		<MxDatepicker format="yyyy-mm-dd hh:ii" type="datetime" :show="showTime" :value="times" :show-tips="true"
			:show-seconds="false" @confirm="handleConfirmTime" @cancel="showTime = false" />
		<SelectUser ref="selectUserRef" @confirm="handleSelectUserConfirm" />
		<TkiTree idKey="code" rangeKey="name" :range="departmentList" ref="tkiTreeDepartRef"
			@confirm="handleTkiTreeDepartConfirm" :multiple="true" />
	</view>
</template>

<script>
import {
	postFormAction,
} from '@/utils/request.js';
import {
	msg_levelList,
	receipt_stateList,
} from './writebox.js'
import MxDatepicker from '../../component/mx-datepicker/mx-datepicker'
import SelectUser from '@/components/selectUser/index.vue'
import FileUpload from '../../component/file-upload/file-upload.vue'
import LEditor from '../../component/l-editor/l-editor.vue'
import TkiTree from '@/components/tki-tree/tki-tree.vue'
import {
	mapState
} from "vuex";
export default {
	components: {
		MxDatepicker,
		SelectUser,
		FileUpload,
		LEditor,
		TkiTree
	},
	data() {
		const that = this
		return {
			msg_levelList,
			receipt_stateList,
			formData: {
				userRealName: "",
				userRealName1: "",
				userRealName2: "",
				title: "",
				content: "",
			},
			rules: {
				userRealName: {
					rules: [{
						required: true,
						errorMessage: `收件人不能为空`,
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}]
				},
				title: {
					rules: [{
						required: true,
						errorMessage: '主题不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}]
				},
			},
			userType: 0, //1 是抄送 2是加密
			url: {
				sendMsg: '/message_oa/sendMsg',
				saveDraft: '/message_oa/saveDraft',
				reply: '/message_oa/reply'
			},
			currentRecord: {}, //当前数据
			ishj: false, //是否高级功能
			iscs: false, //抄送
			isms: false, //密送
			times: null,
			type: '',
			showTime: false,
			departmentList: [], //部门树
			subsectionList: ['发送到人员', '发送到部门'],
			current: 0,
			addressBookDetails: {}, //人员发消息携带收件人信息
		}
	},
	onLoad(options) {
		console.log("options", options)
		this.type = options.type || ''
		if (options.currentRecord) {
			this.currentRecord = JSON.parse(options.currentRecord)
		}
		if (options.addressBookDetails) {
			this.addressBookDetails = JSON.parse(options.addressBookDetails)
		}
		this.getDepartmentsData()
		this.init()
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.form.setRules(this.rules);
	},
	computed: {
		...mapState(["emailType"]),
	},
	methods: {
		handleChangeSendNow(e, col) {
			this.formData[col] = e.detail.value
		},
		init() {
			this.$nextTick(() => {
				console.log("emailType", this.emailType)
				this.formData = {
					receiver: '',
					userRealName: "",
					userRealName1: "",
					receiver1: '',
					userRealName2: "",
					receiver2: '',
					title: "",
					content: "",
					send_now: 'yes',
					send_time: '',
					receiver: '',
					isToOutBox: 'true',
					receipt_state: 0,
					msg_level: 0,
				}
				this.formData.hadUsers = []
				this.formData.hadUsers1 = []
				this.formData.hadUsers2 = []
				this.formData.hadDeptList = []
				console.log("this.currentRecord", this.currentRecord)
				if (this.currentRecord && Object.keys(this.currentRecord).length) {
					this.formData.userRealName = this.currentRecord.receiverRealName;
					this.formData.receiver = this.currentRecord.receiver;
					this.formData.title = this.currentRecord.title;
					if (this.formData.receiver) {
						if (this.formData.receiver.indexOf('dept@') != -1) {
							this.current = 1
							this.formData.hadDeptList.push({
								code: this.formData.receiver.replaceAll('dept@', ''),
								name: this.formData.userRealName,
							});
						} else {
							this.current = 0
							this.formData.hadUsers.push({
								key: this.formData.receiver,
								name: this.formData.receiver,
								title: this.formData.userRealName,
								realName: this.formData.userRealName,
							});
						}
					}
				}
				if (this.addressBookDetails && Object.keys(this.addressBookDetails).length) {
					this.formData.userRealName = this.addressBookDetails.realName;
					this.formData.receiver = this.addressBookDetails.name;
					if (this.formData.receiver) {
						this.current = 0
						this.formData.hadUsers.push({
							key: this.formData.receiver,
							name: this.formData.receiver,
							title: this.formData.userRealName,
							realName: this.formData.userRealName,
						});
					}
				}
				this.$refs.form.clearValidate()
			});
		},
		//高级功能
		handleShowMore() {
			this.ishj = !this.ishj;
		},
		handleCS() {
			this.iscs = !this.iscs;
			if (!this.iscs) {
				this.formData.userRealName1 = '';
				this.formData.receiver1 = '';
				this.formData.hadUsers1 = []
			}
		},
		handleMS() {
			this.isms = !this.isms;
			if (!this.isms) {
				this.formData.userRealName2 = '';
				this.formData.receiver2 = '';
				this.formData.hadUsers2 = []
			}
		},
		//部门时选择是否发送到部门
		sectionChange(e) {
			this.current = e.currentIndex;
			this.formData.userRealName = '';
			this.formData.receiver = '';
			this.formData.hadUsers = []
			this.formData.hadDeptList = []
			if (this.current == 0) {
				this.rules.userRealName.rules[0].errorMessage = '收件人不能为空'
			} else if (this.current == 1) {
				this.rules.userRealName.rules[0].errorMessage = '部门不能为空'
			}
			this.$refs.form.clearValidate()
		},
		//选择人员
		handleSelectUser(type) {
			this.userType = type
			switch (this.userType) {
				case 0:
					this.$refs.selectUserRef.open({
						users: this.formData['hadUsers']
					})
					break;
				case 1:
					this.$refs.selectUserRef.open({
						users: this.formData['hadUsers1']
					})
					break;
				case 2:
					this.$refs.selectUserRef.open({
						users: this.formData['hadUsers2']
					})
					break;
			}
		},
		//选择用户回调
		handleSelectUserConfirm({
			selectUserList,
			label,
			value
		}) {
			console.log("handleSelectUserConfirm", selectUserList)
			switch (this.userType) {
				case 0:
					this.formData.userRealName = label
					this.formData.receiver = value
					if (Array.isArray(this.formData['hadUsers'])) {
						this.formData['hadUsers'] = this.formData['hadUsers'].concat(selectUserList)
					} else {
						this.formData['hadUsers'] = selectUserList
					}
					this.formData.userRealName = this.formData['hadUsers'].map(item => item.title).join(',')
					this.formData.receiver = this.formData['hadUsers'].map(item => item.key).join(',')
					break;
				case 1:
					this.formData.userRealName1 = label
					this.formData.receiver1 = value
					if (Array.isArray(this.formData['hadUsers1'])) {
						this.formData['hadUsers1'] = this.formData['hadUsers1'].concat(selectUserList)
					} else {
						this.formData['hadUsers1'] = selectUserList
					}
					this.formData.userRealName1 = this.formData['hadUsers1'].map(item => item.title).join(',')
					this.formData.receiver1 = this.formData['hadUsers1'].map(item => item.key).join(',')
					break;
				case 2:
					this.formData.userRealName2 = label
					this.formData.receiver2 = value
					if (Array.isArray(this.formData['hadUsers2'])) {
						this.formData['hadUsers2'] = this.formData['hadUsers2'].concat(selectUserList)
					} else {
						this.formData['hadUsers2'] = selectUserList
					}
					this.formData.userRealName2 = this.formData['hadUsers2'].map(item => item.title).join(',')
					this.formData.receiver2 = this.formData['hadUsers2'].map(item => item.key).join(',')
					break;
			}
		},
		//删除已选用户
		handleCloseTag(index, type) {
			switch (type) {
				case 0:
					this.formData['hadUsers'].splice(index, 1)
					this.formData.userRealName = this.formData['hadUsers'].map(item => item.title).join(',')
					this.formData.receiver = this.formData['hadUsers'].map(item => item.key).join(',')
					break;
				case 1:
					this.formData['hadUsers1'].splice(index, 1)
					this.formData.userRealName1 = this.formData['hadUsers1'].map(item => item.title).join(',')
					this.formData.receiver1 = this.formData['hadUsers1'].map(item => item.key).join(',')
					break;
				case 2:
					this.formData['hadUsers2'].splice(index, 1)
					this.formData.userRealName2 = this.formData['hadUsers2'].map(item => item.title).join(',')
					this.formData.receiver2 = this.formData['hadUsers2'].map(item => item.key).join(',')
					break;
				case 3:
					this.formData['hadDeptList'].splice(index, 1)
					this.formData.userRealName = this.formData['hadDeptList'].map(item => item.name).join(',')
					this.formData.receiver = this.formData['hadDeptList'].map(item => `dept@${item.code}`).join(',')
					break;

			}
		},
		//回调时间
		handleConfirmTime(e) {
			console.log("handleConfirmTime", e)
			const {
				value
			} = e
			this.formData.send_time = value
			this.showTime = false
		},
		//选择部门
		handleTkiTreeDepart() {
			this.$refs.tkiTreeDepartRef._show()
		},
		//部门回调
		handleTkiTreeDepartConfirm(e) {
			let departmentSelected = []
			if (e && e.length) {
				departmentSelected = e
			}
			if (departmentSelected && departmentSelected.length) {
				const codes = this.formData['hadDeptList'].map(item => item.code)
				departmentSelected.forEach(item => {
					if (!codes.includes(item.code)) {
						this.formData['hadDeptList'].push(item)
					}
				})
			}
			this.formData.userRealName = this.formData['hadDeptList'].map(item => item.name).join(',')
			this.formData.receiver = this.formData['hadDeptList'].map(item => `dept@${item.code}`).join(',')


		},
		getDepartmentsData() {
			try {
				let params = {};
				postFormAction('/department/getDepartments', params).then((res) => {
					const {
						data
					} = res
					this.departmentList = data || [];
				});
			} catch (e) {
				console.error(e)
			} finally { }
		},
		handleReturn() {
			var pages = getCurrentPages();
			// var currPage = pages[pages.length - 1]; //当前页面
			var prevPage = pages[pages.length - 2]; //上一个页面
			console.log("prevPage", prevPage)
			if (prevPage.$vm && prevPage.$vm._ && prevPage.$vm._.exposeProxy) {
				prevPage.$vm._.exposeProxy.isRefresh = true
			}
			uni.navigateBack()
		},
		//重写
		handleResetWrite() {
			this.init()
		},
		//确定
		handleSend(type) {
			console.log("this.formData", this.formData)
			this.$refs.form.validate(async valid => {
				console.log('验证通过');
				try {
					this.formData.content = this.$refs.lEditorRef.content
					if (!this.formData.content) {
						uni.showToast({
							title: '请输入正文',
							icon: 'none'
						})
						return
					}
					const data = Object.assign({}, this.formData);
					delete data.hadUsers
					delete data.hadUsers1
					delete data.hadUsers2
					delete data.hadDeptList
					delete data.att
					if (this.current == 1) {
						data.isDept = true
					}
					const fileList = this.$refs.fileUploadRef.fileList
					console.log('fileList', fileList);
					// const files = []
					if (fileList && fileList.length) {
						data.attachments = fileList.map(item => item.id).join(',')
						// fileList.forEach((item, index) => {
						// files.push({
						// 	[`att${index + 1}`]: item,
						// 	name: 'file',
						// 	uri: item.tempFilePath
						// })
						// });
					}
					console.log('data', data);
					uni.showLoading({
						title: '加载中',
						mask: true
					});
					let res = {}
					if (type == 'send') {
						res = await postFormAction(this.url.sendMsg, data);
					} else if (type == 'draft') {
						res = await postFormAction(this.url.saveDraft, data);
					} else if (type == 'reply') {
						res = await postFormAction(this.url.reply, data);
					}

					if (res.code == 200) {
						uni.showToast({
							title: '操作成功',
							icon: 'none'
						})
						this.handleReturn();
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				} catch (error) {
					console.log('handleSend', error);
				} finally {
					uni.hideLoading()
				}
			}).catch(err => {
				console.log('err', err);
			})

		}
	}
}
</script>

<style lang="scss" scoped>
.content {
	overflow-y: auto;

	&_form {
		padding: 20rpx 20rpx 0;
		margin-bottom: 100rpx;
	}
}

.body_bottom {
	position: fixed;
	z-index: 10;
	bottom: 0;
	height: 100rpx;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-around;
	gap: 20rpx;
	background: #FFFFFF;
	box-shadow: 0rpx -2rpx 16rpx 0rpx rgba(0, 0, 0, 0.1);
}
</style>